<?php
require_once('config.php');
function __autoload($class) {
    global $classFolder;
    require_once($classFolder. $class. ".class.php");
} 

        set_time_limit(0);
        global $db;
        $db = new db($mysqlSettings);
        $db->connect(true);
        $db->enableErrors();
        $table = $db->getTable('boxes');
        $JSONdata = array();
        
        for(;;) {
            $data = $db->get("SELECT * FROM $table");
            if(is_array($data)) {
                $boxes = count($data);
                
                foreach($data as $boxItem) {
                    if($boxItem['new_data'] == 1) {
                        $newData = true;                        
                        $JSONdata['boxCommands'][] = array("userid" => $boxItem['userid'], "command" => $boxItem['json']);
                        if($boxItem['json'] == 300) {
                            $userIdDel = $boxItem['userid'];
                            $db->run("DELETE FROM $table WHERE userid=$userIdDel");    
                        }
                    }
                }
            }
            if($newData) {
                $JSONdata["boxCount"] = $boxes;
                newData($JSONdata);
                break;
            }
            usleep(800);
        }
        
function newData($data) {
            global $db;
            $json = $data;
            $boxCmd = $data['boxCommands'];
            
            foreach($boxCmd as $key => $items) {
                $userid = $items['userid'];
                $db->update('boxes', array("json" => 0, "new_data" => 0), "userid=$userid");
            }
            echo json_encode($json);
            flush();
    }
  ?>